<?php
require_once 'application/libraries/ChartboostApiClient.php';

class ChartboostModel extends AdClientModel {

	
	public function __construct() {
		$this->filter = new ChartBoostFilter();
	}


	public function getData($operation,$email,$id,$time_period,$time_dim = 'day',$data_needed) {
		$this->getUserAccountData($email);
		if ($this->api == NULL) {
			$this->api = new ChartboostApiClient($this->session->userdata("chartBoostUserId"),
					$this->session->userdata("chartBoostUserSig"));
		}
		$arr_response = array();
		try {
			$response = $this->execute($operation,$id, $time_period,$time_dim);
			$response = $this->filter->extract($response);
			MessagingHelper::AddToData($arr_response, $response);
		} catch (ApiException $ex) {
			$error_msg = $ex->getMessage();
			MessagingHelper::AddToError($arr_response,ErrorMessgaes::$USER_ACOUNT_CHARTBOOST_CODE ,$error_msg);
		} catch (Exception $ex2) {
			MessagingHelper::AddToError($arr_response,ErrorMessgaes::$INERTNAL_CODE, ErrorMessgaes::$INERTNAL_MSG);
		}
		return $arr_response;
	}

	private function execute($operation,$id, $time_period,$time_dim) {
		if ($time_dim === 'day') {
			$time_dimension = ChartboostApiClient::DIMENSION_DAY;
		} elseif ($time_dim === 'week') {
			$time_dimension = ChartboostApiClient::DIMENSION_WEEK;
		} elseif ($time_dim === 'month') {
			$time_dimension = ChartboostApiClient::DIMENSION_MONTH;
		}
		switch ($operation) {
			case 'statistics':
				return $this->getSiteStatsData($id, $time_period,$time_dimension);
				break;
			case 'search':
				return $this->getSiteSearchData($id);
				break;
		}
	}

	protected function getUserAccountData($email) {
		$sql = "SELECT users_account_chartboost.user_sig,users_account_chartboost.user_id FROM users_account_chartboost WHERE email = ?";
		$query = $this->db->query($sql, array($email));
		if ($query->num_rows() > 0) {
			$row = $query->row();
			$this->session->set_userdata(array('chartBoostUserId' => ($row->user_id), 'chartBoostUserSig' => ($row->user_sig)));
		} else {
			throw new Exception('Problem fetching acount data');
		}
	}

	protected function getSiteStatsData($site_id_array, $time_period,$time_dimension) {

		$start_date = DayHelper::getGmdate($time_period);
		$end_date = gmdate('Y-m-d'); // today


		$params = array(
				'date_min' => $start_date,
				'date_max' => $end_date,
				'aggregate' => $time_dimension,
				'group_by' => 'date'
		);

		if (!empty($site_id_array)) {
			$params['app_ids'] = $site_id_array;
		}

			
		$data = $this->api->getData('apps', 'analytics', $params, false);
		return $data;
	}

	protected function getSiteSearchData($id) {

		$params = array();
		if ($id) {
			$params['app_id'] = $id;
		}
		$data = $this->api->getData('apps',null, $params, false);
		return $data;

	}




}
